package mock;

import cn.ibabygroup.commons.authority.exception.AuthException;
import cn.ibabygroup.commons.authority.util.ErrorCode;
import cn.ibabygroup.commons.authority.util.SecurityUtil;
import mock.entity.Parameter;
import mock.entity.TestDataForm;
import org.json.JSONObject;
import org.junit.Assert;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Crowhyc on 2016/5/25.
 */
public class UserLogin extends TestDataForm {
    public UserLogin() {
        this.setHttpMethod("POST");
        this.setUrl("/user/login");
        List<Parameter> parameters = new ArrayList<>();
        parameters.add(new Parameter("username", "admin", "String"));
        parameters.add(new Parameter("password", "123456", "String"));
        this.setRequestParams(parameters);
    }

    @Override
    public void before() {

    }

    @Override
    public void after() {

    }

    @Override
    public void specialProcess(MvcResult result) throws Exception {
        JSONObject jsonObject = new JSONObject(result.getResponse().getContentAsString());
        Assert.assertNotNull(jsonObject.getString("Data"));
        Assert.assertTrue(checkToken(jsonObject.getString("Data")));
    }

    private boolean checkToken(String token) throws Exception {
        String key = "Share2015&IBaby1";
        if (StringUtils.isEmpty(token) || token.equals("null"))
            throw new AuthException("没有找到token", ErrorCode.TOKEN_NOT_FOUND);
        String tokenStr = SecurityUtil.decrypt(token, key);
        if (StringUtils.isEmpty(tokenStr))
            throw new AuthException("解析token异常", ErrorCode.TOKEN_INVALID);
        if (tokenStr.length() < 14)
            throw new AuthException("token长度不够", ErrorCode.TOKEN_INVALID);
        if (tokenStr.length() == 14)
            throw new AuthException("没有找到证书信息", ErrorCode.TOKEN_INVALID);
        String dCertStr = tokenStr.substring(0, tokenStr.length() - 14);
        String certStr = SecurityUtil.decrypt(dCertStr, key);
        if (StringUtils.isEmpty(certStr))
            throw new AuthException("解析证书信息异常", ErrorCode.SYS_ERROR);
        String s = "";
        return true;
    }
}
